import axios from "axios";
import Refresh from "./../utils/refreshToken.js";
import router from './../router'
import { ElMessage } from "element-plus";

// let baseUrl = import.meta.env.VITE_APP_BASE_API;
let baseUrl = window.location.protocol + '//' + window.location.host +'/adminweb'
console.log(baseUrl);
let urlsAndData = [];



const instance = axios.create({
	headers: {
		"Content-Type": "application/json;charset=utf8",
	},
	baseURL: baseUrl,
	timeout: 30000,
	withCredentials: false,
});

// 添加请求拦截器
instance.interceptors.request.use(
	(config) => {
		var username = localStorage.getItem("username");
		var token = localStorage.getItem("token");
		if (username && token) {
			config.headers["AUTH-TOKEN"] = username + "|" + token;
		}
		return config;
	},
	(error) => {}
);

// 添加响应拦截器
instance.interceptors.response.use(
	async (response) => {
		// 对响应数据做些事
		if (response.status === 200) {
			if (response.data && response.data.code === 0) {
				return response; // 在请求成功后可以对返回的数据进行处理，再返回到前台
			} else if (response.data && response.data.code == -56055) {
				ElMessage.closeAll();
				ElMessage({
					message: "登录已过期，请重新登录！",
					type: "error",
        });
        setTimeout(() => {
          router.push('/login')
        },3000)
				return Promise.reject(response.data);
			}
		}
		return response;
	},
	(error) => {
		//router.push("/login");
		//  console.log(error.response.data);
		return Promise.reject(error.response.data); // 返回接口返回的错误信息
	}
);

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function getData(url, data) {
	return new Promise((resolve, reject) => {
		instance
			.get(url, {
				params: data,
			})
			.then((res) => {
				if (res.data.code == -56055) {
					reject("token失效");
				} else {
					resolve(res.data);
				}
			})
			.catch(async (err) => {
				if (localStorage.getItem("password")) {
					let password = Refresh.decrypt(localStorage.getItem("password"));
					let start = 1;
					if (urlsAndData.length == 0) {
						urlsAndData.push({
							url: baseUrl + "/adminweb/sys/admin/login",
							data: {
								user_name: localStorage.getItem("username"),
								user_pwd: password,
							},
							time: new Date().getTime(),
							type: "refresh",
							headers: {},
							token: localStorage.getItem("token"),
						});
						start = 0;
					}
					let nowTime = new Date().getTime();

					if (
						urlsAndData.length > 0 &&
						urlsAndData[0].type == "refresh" &&
						(nowTime - urlsAndData[0].time) / 1000 >= 3600
					) {
						start = 0;
						urlsAndData[0].time = new Date().getTime();
					}
					urlsAndData.push({
						url: baseUrl + url,
						data: data || {},
						time: new Date().getTime(),
						type: "get",
						refresh: false,
					});

					for (let i = start; i < urlsAndData.length; i++) {
						if (i == 0) {
							urlsAndData[0]["token"] = "";
							let res = await axios.post(
								urlsAndData[0]["url"],
								urlsAndData[0]["data"]
							);
							urlsAndData[0]["token"] = res.data?.datas?.token;
							localStorage.setItem("token", urlsAndData[0]["token"]);
						} else {
							if (
								urlsAndData[0]["token"] != "" &&
								urlsAndData[i]["refresh"] == false
							) {
								await axios
									.get(
										urlsAndData[i]["url"],
										{
											params: urlsAndData[i]["data"],
										},
										{
											headers: {
												"AUTH-TOKEN":
													localStorage.getItem("username") +
													"|" +
													urlsAndData[0]["token"],
											},
										}
									)
									.then((res) => {
										urlsAndData[i]["refresh"] = true;
										resolve(res.data);
									})
									.catch((err) => {
										urlsAndData[i]["refresh"] = false;
										reject(err);
									});
							}
						}
					}

					urlsAndData = urlsAndData.filter(
						(item) => item.refresh == false || item.type == "refresh"
					);
					/*let password = Refresh.decrypt(localStorage.getItem("password"))
                    await axios.post(baseUrl+"/adminweb/sys/admin/login", {
                        user_name: localStorage.getItem("username"),
                        user_pwd: password,
                    }).then(async res=> {
                        tokenRefresh = res?.datas?.token
                        localStorage.setItem("token", tokenRefresh);

                    }).catch(err => {
                        console.log(err)
                    })
                    var username = localStorage.getItem("username");
                    var token = localStorage.getItem("token");
                    await axios.get(baseUrl+url, {
                        params: data
                    }, {
                        headers:{
                            "AUTH-TOKEN": username + "|" + token
                        }
                    })
                        .then(res => {
                            // console.log(res.data);
                            resolve(res.data);
                        }).catch(err=> {
                        reject(err)
                    })*/
				}
			});
	});
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} data [请求时携带的参数]
 * @param {Object} config 配置参数
 */
export function postData(url, data, config) {
	return new Promise((resolve, reject) => {
		instance
			.post(url, data, config)
			.then((res) => {
				if (res.data.code == -56055) {
					reject("token失效");
				} else {
					resolve(res.data);
				}
			})
			.catch(async (err) => {
				if (localStorage.getItem("password")) {
					let password = Refresh.decrypt(localStorage.getItem("password"));
					let start = 1;
					if (urlsAndData.length == 0) {
						urlsAndData.push({
							url: baseUrl + "/adminweb/sys/admin/login",
							data: {
								user_name: localStorage.getItem("username"),
								user_pwd: password,
							},
							time: new Date().getTime(),
							type: "refresh",
							headers: {},
							token: localStorage.getItem("token"),
						});
						start = 0;
					}
					let nowTime = new Date().getTime();

					if (
						urlsAndData.length > 0 &&
						urlsAndData[0].type == "refresh" &&
						(nowTime - urlsAndData[0].time) / 1000 >= 3600
					) {
						start = 0;
						urlsAndData[0].time = new Date().getTime();
					}
					urlsAndData.push({
						url: baseUrl + url,
						data: data || {},
						time: new Date().getTime(),
						type: "post",
						refresh: false,
					});

					for (let i = start; i < urlsAndData.length; i++) {
						if (i == 0) {
							urlsAndData[0]["token"] = "";
							let res = await axios.post(
								urlsAndData[0]["url"],
								urlsAndData[0]["data"]
							);
							urlsAndData[0]["token"] = res.data?.datas?.token;
							localStorage.setItem("token", urlsAndData[0]["token"]);
						} else {
							if (
								urlsAndData[0]["token"] != "" &&
								urlsAndData[i]["refresh"] == false
							) {
								await axios
									.post(urlsAndData[i]["url"], urlsAndData[i]["data"], {
										headers: {
											"AUTH-TOKEN":
												localStorage.getItem("username") +
												"|" +
												urlsAndData[0]["token"],
										},
									})
									.then((res) => {
										urlsAndData[i]["refresh"] = true;
										resolve(res.data);
									})
									.catch((err) => {
										urlsAndData[i]["refresh"] = false;
										reject(err);
									});
							}
						}
					}

					urlsAndData = urlsAndData.filter(
						(item) => item.refresh == false || item.type == "refresh"
					);

					/*                        let res = await axios
                            .post(baseUrl+"/adminweb/sys/admin/login", {
                                user_name: localStorage.getItem("username"),
                                user_pwd: password,
                            })
                        window.tokenRefresh = res.data?.datas?.token
                        localStorage.setItem("token", window.tokenRefresh);

                        if(window.tokenRefresh){
                            var username = localStorage.getItem("username");
                            var token = localStorage.getItem("token");
                            await axios
                                .post(baseUrl+url, data, {
                                    headers:{
                                        "AUTH-TOKEN": username + "|" + token
                                    }
                                })
                                .then(res => {
                                    // console.log(res.data);
                                    resolve(res.data);
                                }).catch(err=> {
                                    reject(err)
                                })
                        }*/
				}
			});
	});
}
